package threads;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {
    //permits表示有多少个授权
    //fair表示是否是公平的，公平的情况下就需要排队
    static Semaphore semaphore = new Semaphore(1,true);
    public static void main(String[] args) {
        new Thread(() -> {
            try {
                /*
                 * 取得授权
                 */
                semaphore.acquire();
                System.out.println("T1 running...");
                Thread.sleep(200);
                System.out.println("T1 end.");
                /*
                 * 释放授权
                 */
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("T2 running...");
                Thread.sleep(200);
                System.out.println("T2 end.");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
